#include "highspeed.h"
#include "base64.h"
#include <iostream>
#include <fstream>

extern "C" {
#include "campro.h"
}

using namespace std;

namespace highspeed
{

static long base64_encode_file_alloc(const char *file, char **out)
{
    filebuf *pbuf;
    ifstream filess;
    long size;
    long out_size;
    char *buffer;

    filess.open (file, ios::binary);
    pbuf = filess.rdbuf();
 
    size = pbuf->pubseekoff (0, ios::end, ios::in);
 
    pbuf->pubseekpos (0, ios::in);
    buffer = new char[size];
 
    pbuf->sgetn (buffer, size);
 
    filess.close();
    out_size = base64_encode_alloc (buffer, size, out);

    delete [] buffer;

    return out_size;
}

int init()
{
    int ret = HIGH_InitSDK();

    if (ret) {
        cerr << "HighSpeed Init error!" << endl;
    }

    return ret > 0 ? -1 : ret;
}

int getStatus()
{
    int ret;

    HIGH_GetStatus(&ret);

    return ret;
}

int close()
{
    int ret = HIGH_StopCamera();

    if (ret) {
        cerr << "HighSpeed close error!" << endl;
    }

    return ret > 0 ? -1 : ret;
}

char *takePicture(const char *file, int width, int height)
{
    char *buff;

    HIGH_SetCameraPixel(width, height);
    HIGH_TakePicture(file);

    base64_encode_file_alloc(file, &buff);

    return buff;
}

int setPixel(int h, int v)
{
    return HIGH_SetCameraPixel(h, v);
}

int setColorStyle(int style)
{
    if (style < 0 || style > 2)
        return -1;

    return HIGH_SetColorType(style);
}

int setColorStyle(ColorStyle style)
{
    return HIGH_SetColorType(style);
}

int rotate(int rotate)
{
    if (rotate < 0 || rotate > 3)
        return -1;

    return HIGH_SetRotateSize(rotate);
}

int rotate(RotationType rotate)
{
    return HIGH_SetRotateSize(rotate);
}

int setZoomScale(int scale)
{
    if (scale < -5 || scale > 5)
        return -1;

    return HIGH_SetZoomView(scale);
}

int setDPI(int dpi)
{
    return HIGH_SetPicDPI(dpi);
}

} // namespace highspeed
